package com.buddy.learn.network.socekt;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author WongZP
 * @date 2022/4/17
 */
public class SocketServer {

    public static void main(String[] args) {
        // 创建 server socket 对象
        try {
            ServerSocket serverSocket = new ServerSocket(8088);
            System.out.println("server start ...");
            Socket socket = serverSocket.accept();
            System.out.println("someone connected ...");
            handle(socket);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }


    }

    private static void handle(Socket socket) {
        try {
            // 从连接中读取数据
            InputStream inputStream = socket.getInputStream();
            byte[] b = new byte[1024];
            int read = inputStream.read(b);
            System.out.println(" client:" + new String(b, 0, read));
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("hi,client".getBytes(StandardCharsets.UTF_8));

        } catch (IOException ioException) {
            ioException.printStackTrace();
        }

    }
}
